package mamikeji.liaowa.ui.activity.clock;

import android.app.Dialog;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Vibrator;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import mamikeji.liaowa.R;
import mamikeji.liaowa.bean.ClockBean;
import mamikeji.liaowa.ui.activity.BaseActivity;
import mamikeji.liaowa.ui.adapter.ClockListAdapter;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MultiStateView;
import mamikeji.liaowa.widget.clock.AlarmService;
import mamikeji.liaowa.widget.clock.Model.AlarmModel;
import mamikeji.liaowa.widget.clock.data.MyAlarmDataBase;
import mamikeji.liaowa.widget.floatingactionbutton.FloatingActionButton;
import mamikeji.liaowa.widget.refreshView.PtrlDownRefreshFrameLayout;

public class ClockListActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.multiStateView_clock_list)
    MultiStateView multiStateViewClockList;
    private ListView listView_clocklist_date;
    private PtrlDownRefreshFrameLayout ptrlDownRefreshFrameLayout_clocklist_date;

    private FloatingActionButton multiple_clock_add;
    private RelativeLayout relativeLayout_clock_dig_query, relativeLayout_clock_dig_btnerror;

    List<ClockBean> clockBeenList;

    private ClockListAdapter clockListAdapter;
    private MyAlarmDataBase db;

    private Dialog dialog_delete;

    public int positions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clock_list);
        ButterKnife.bind(this);
        getBase();
        setTitleLeftBtn();
        setTitleName(R.string.clock_date_name);
        setTitleRightImage(R.drawable.icon_shanchunaozhong_n, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /**震动服务*/
                Vibrator vib = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
                vib.vibrate(50);//只震动一秒，一次

                clockListAdapter.boolAnim = !clockListAdapter.boolAnim;
                clockListAdapter.notifyDataSetChanged();
                if (clockListAdapter.boolAnim) {
                    // 在代码中实现列表动画
                    Animation animation = (Animation) AnimationUtils.loadAnimation(
                            ClockListActivity.this, R.anim.anim_list_clock_delete);
                    LayoutAnimationController lac = new LayoutAnimationController(animation);
                    lac.setDelay(0.4f);  //设置动画间隔时间
                    lac.setOrder(LayoutAnimationController.ORDER_NORMAL); //设置列表的显示顺序
                    listView_clocklist_date.setLayoutAnimation(lac);  //为ListView 添加动画

                }
            }
        });
        init();
        initDate();
        showDeleteDialog();
    }

    private void init() {
        ptrlDownRefreshFrameLayout_clocklist_date = (PtrlDownRefreshFrameLayout) findViewById(R.id.ptrlDownRefreshFrameLayout_clocklist_date);
        multiple_clock_add = (FloatingActionButton) findViewById(R.id.multiple_clock_add);
        listView_clocklist_date = (ListView) findViewById(R.id.listView_clocklist_date);

        clockBeenList = new ArrayList<>();
        clockListAdapter = new ClockListAdapter(clockBeenList, this);
        listView_clocklist_date.setAdapter(clockListAdapter);

        ptrlDownRefreshFrameLayout_clocklist_date.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, listView_clocklist_date, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                initDate();
            }
        });
        listView_clocklist_date.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ClockBean item = (ClockBean) clockListAdapter.getItem(i);
                if (!clockListAdapter.boolAnim) {
                    Intent intent = new Intent(ClockListActivity.this, EditClockActivity.class);
                    intent.putExtra(EditClockActivity.CLOCK_PARENT_ID, item.getParentID());
                    startActivityForResult(intent, 101);
                }
            }
        });

        clockListAdapter.setOnItemClickListener(new ClockListAdapter.OnItemClickListener() {
            @Override
            public void onClockClick(int position, View view) {
                MobclickAgent.onEvent(ClockListActivity.this,"PregntAlarmClockCloseButton");//孕育闹钟-关闭按钮
                ImageView imageView = (ImageView) view;
                db = new MyAlarmDataBase(getApplicationContext());
                List<AlarmModel> mAlarmList = db.getAlarmsList(clockBeenList.get(position).getParentID());

                if (mAlarmList.get(0).getmActive().equals("true")) {
                    for (AlarmModel model : mAlarmList) {
                        model.setmActive("false");
                        db.updateAlarm(model);
                        cancelAlarm(ClockListActivity.this, model.getId(), model);
                    }
                    ForToast.showToast("已关闭闹钟！");
                    imageView.setImageResource(R.drawable.icon_guanbi);
                } else if (mAlarmList.get(0).getmActive().equals("false")) {
                    for (AlarmModel model : mAlarmList) {
                        model.setmActive("true");
                        db.updateAlarm(model);
                        restartAlarm(model.getTime(), model.getWeek(), model.getId());
                    }
                    ForToast.showToast("已开启闹钟！");
                    imageView.setImageResource(R.drawable.icon_dakai_n);
                }
            }

            @Override
            public void onDeleteClick(int position) {
                ClockListActivity.this.positions = position;
                dialog_delete.show();
            }
        });

        multiple_clock_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clockListAdapter.boolAnim = false;
                clockListAdapter.notifyDataSetChanged();
                startActivity(new Intent(ClockListActivity.this, ClockTypeActivity.class));
            }
        });
    }

    private ServiceConnection connection = null;
    private AlarmService.MyBinder binder;

    /**
     * 绑定闹钟服务
     *
     * @param time
     * @param repeat
     * @param id
     */
    private void restartAlarm(final String time, final String repeat, final int id) {

        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                binder = (AlarmService.MyBinder) service;
                switch (repeat) {
                    case "只响一次":
                        binder.setSingleAlarm(getApplicationContext(), time, id);
                        break;
                    default:
                        AlarmModel model = db.getAlarm(id);
                        String repeatCode = model.getWeekCode();
                        binder.setDiyAlarm(getApplicationContext(), repeat, time, id, repeatCode);
                }

                Log.d("MainActivity", "重启闹钟");
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.d("MainActivity", "解绑服务");
            }
        };
        Intent intent = new Intent(this, AlarmService.class);
        bindService(intent, connection, BIND_AUTO_CREATE);

        unbindService(connection);
    }

    /**
     * 解绑服务
     *
     * @param context
     * @param id
     * @param alarm
     */
    public void cancelAlarm(final Context context, final int id, final AlarmModel alarm) {

        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                binder = (AlarmService.MyBinder) service;
                binder.cancelAlarm(alarm, id, context);
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.d("MainActivity", "解绑服务");
            }
        };
        Intent intent = new Intent(this, AlarmService.class);

        bindService(intent, connection, BIND_AUTO_CREATE);

        Log.d("MainActivity", "取消闹钟");

        unbindService(connection);

    }

    private void initDate() {
        db = new MyAlarmDataBase(getApplicationContext());
        List<AlarmModel> mAlarmList = db.getAllAlarms();

        ptrlDownRefreshFrameLayout_clocklist_date.refreshComplete();

        List<String> stringList = new ArrayList<>();
        for (int i = 0; i < mAlarmList.size(); i++) {
            stringList.add(mAlarmList.get(i).getParentID());
        }

        stringList = removeDuplicateWithOrder(stringList);

        clockBeenList = new ArrayList<>();
        for (int i = 0; i < stringList.size(); i++) {
            clockBeenList.add(new ClockBean(0, "", "", "", new ArrayList<String>(), new ArrayList<String>(), "", "", "", "", ""));
        }

        for (int i = 0; i < stringList.size(); i++) {
            for (int j = 0; j < mAlarmList.size(); j++) {
                if (stringList.get(i).equals(mAlarmList.get(j).getParentID())) {

                    List<String> timeList = clockBeenList.get(i).getTime();
                    timeList.add(mAlarmList.get(j).getTime());
                    clockBeenList.get(i).setTime(timeList);

                    clockBeenList.get(i).setId(mAlarmList.get(j).getId());
                    clockBeenList.get(i).setUsercode(mAlarmList.get(j).getUsercode());
                    clockBeenList.get(i).setTypeName(mAlarmList.get(j).getTypeName());
                    clockBeenList.get(i).setTimeGuid(mAlarmList.get(j).getTimeGuid());

                    List<String> weekList = new ArrayList<>();
                    if (mAlarmList.get(j).getWeekCode() != null) {
                        if (mAlarmList.get(j).getWeekCode().contains(",")) {
                            String[] mTimeSplit = mAlarmList.get(j).getWeekCode().split(",");
                            for (int m = 0; m < mTimeSplit.length; m++) {
                                weekList.add(mTimeSplit[m]);
                            }
                        } else {
                            weekList.add(mAlarmList.get(j).getWeekCode());
                        }
                    }
                    clockBeenList.get(i).setWeek(weekList);
                    clockBeenList.get(i).setWeekCode(mAlarmList.get(j).getWeekCode());
                    clockBeenList.get(i).setmWakeType(mAlarmList.get(j).getmWakeType());
                    clockBeenList.get(i).setmActive(mAlarmList.get(j).getmActive());
                    clockBeenList.get(i).setmRing(mAlarmList.get(j).getmRing());
                    clockBeenList.get(i).setParentID(mAlarmList.get(j).getParentID());
                }
            }
        }


        if (clockBeenList.size() > 0){
            multiStateViewClockList.setViewState(MultiStateView.VIEW_STATE_CONTENT);
            clockListAdapter.setList(clockBeenList);
        }else {
            multiStateViewClockList.setViewState(MultiStateView.VIEW_STATE_EMPTY);
        }
    }

    //去重
    public List removeDuplicateWithOrder(List list) {
        Set set = new HashSet();
        List newList = new ArrayList();
        for (Iterator iter = list.iterator(); iter.hasNext(); ) {
            Object element = iter.next();
            if (set.add(element))
                newList.add(element);
        }
        return newList;
    }

    /**
     * 确认删除
     */
    private void showDeleteDialog() {
        dialog_delete = new Dialog(ClockListActivity.this, R.style.DialogLoading);
        View inflate = LayoutInflater.from(ClockListActivity.this).inflate(R.layout.diglog_clock_delete, null);
        dialog_delete.setContentView(inflate);

        relativeLayout_clock_dig_query = (RelativeLayout) inflate.findViewById(R.id.relativeLayout_clock_dig_query);
        relativeLayout_clock_dig_btnerror = (RelativeLayout) inflate.findViewById(R.id.relativeLayout_clock_dig_btnerror);

        relativeLayout_clock_dig_query.setOnClickListener(this);
        relativeLayout_clock_dig_btnerror.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.relativeLayout_clock_dig_btnerror:
                dialog_delete.hide();
                break;
            case R.id.relativeLayout_clock_dig_query:
                dialog_delete.hide();
                List<AlarmModel> alarmsList = db.getAlarmsList(clockBeenList.get(positions).getParentID());
                for (AlarmModel alarm : alarmsList) {
                    db.deleteAlarm(alarm);
                    cancelAlarm(ClockListActivity.this, alarm.getId(), alarm);
                }
                int num = ForPreference.getInt(ForContents.APP_CLOCK_COUNT) - 1;
                ForPreference.putInt(ForContents.APP_CLOCK_COUNT, num);
                initDate();
                break;
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        clockBeenList.clear();
        initDate();
    }

}